class View extends egret.Bitmap {
	private _hp: number;			//当前血量
	private _pos: egret.Point;		//位置
	private _target: View;			//攻击目标
	private _id: number;			//agent中的id
	private _atkTime: number;		//攻击时间

	private _startId: number;		//敌人开始id
	private _endId: number;			//敌人结束id
	public constructor() {
		super();

		this._hp = Consts.MAX_HP;
		this._pos = new egret.Point();
		this._target = null;
		this._id = null;
		this._atkTime = Consts.ATK_TIME;
	}

	public init(res: string): void {
		RES.getResAsync(res, () => {
            let tex = RES.getRes(res);
            this.texture = tex;
        }, this);

		this.scaleX = 0.2;
		this.scaleY = 0.2;
	}

	public setId(id: number): void {
		this._id = id;
	}

	public setPos(px: number, py: number): void {
		this.x = px;
		this.y = py;
	}

	public setEnemyRange(startId: number, endId: number) : void {
		this._startId = startId;
		this._endId = endId;
	}

	public update(dt): void {
		if (!this._target) {
			this.findTarget();
		}

		if (!this._target) {
			return;
		}

		this._atkTime -= dt;
		if (this._atkTime <= 0) {
			this._atkTime = Consts.ATK_TIME;
			this.atk();
		}
	}

	public findTarget(): void {
		let mapLayer = RvoExample.getIt().getMapLayer();
		let views = mapLayer.getViews();

		let dis = 0;
		let target = null;
		//在地方寻找距离最短的敌军
		for (let key in  views) {
			let view = views[key];
			let id = view.getId();
			if (id >= this._startId && id <= this._endId) {
				let temp = egret.Point.distance(view.getPos(), this.getPos())
				if (dis == 0 || temp < dis) {
					dis = temp;
					target = view;
				}
			}
		}

		this._target = target;
	}

	public setTarget(view: View): void {
		this._target = view;
	}

	public delHp(hp: number): void {
		this._hp -= hp;

		if (this._hp <= 0) {
			let mapLayer = RvoExample.getIt().getMapLayer();
			mapLayer.deathView(this.getId());
		}
	}

	public atk(): void {
		let tPos = this._target.getPos();
		let dis = egret.Point.distance(this.getPos(), tPos);
		
		if (dis < 20) {
			let delHp = Consts.ATK_HP;
			this._target.tint = 0x00ff00;
			this._target.delHp(delHp);
		}
	}

	public getPos(): egret.Point {
		this._pos.setTo(this.x, this.y);
		return this._pos;
	}

	public getTargetView(): View {
		return this._target;
	}

	public getId(): number {
		return this._id;
	}

	public destroy(): void {
		this._target = null;

		if (this.parent) {
			this.parent.removeChild(this);
		}
	}
}